<template>
  <div v-if="!item.meta?.hidden">
    <!-- 没有子菜单的情况，直接显示菜单项 -->
    <el-menu-item 
      v-if="!item.children || item.children.length === 0"
      :index="resolvePath(item.path)"
    >
      <el-icon v-if="item.meta?.icon">
        <component :is="item.meta.icon" />
      </el-icon>
      <template #title>
        <span>{{ item.meta?.title }}</span>
      </template>
    </el-menu-item>

    <!-- 有子菜单的情况 -->
    <el-sub-menu 
      v-else 
      :index="resolvePath(item.path)"
      :popper-class="isCollapse ? 'collapse-popper' : ''"
    >
      <template #title>
        <el-icon v-if="item.meta?.icon">
          <component :is="item.meta.icon" />
        </el-icon>
        <span v-if="!isCollapse">{{ item.meta?.title }}</span>
      </template>
      
      <!-- 递归渲染子菜单 -->
      <sidebar-item
        v-for="child in item.children"
        :key="child.path"
        :item="child"
        :base-path="resolvePath(item.path)"
        :is-collapse="isCollapse"
      />
    </el-sub-menu>
  </div>
</template>

<script setup>
import { isExternal } from '@/utils/validate'

const props = defineProps({
  item: {
    type: Object,
    required: true
  },
  basePath: {
    type: String,
    default: ''
  },
  isCollapse: {
    type: Boolean,
    default: false
  }
})

/**
 * 修正的路径解析方法
 */
const resolvePath = (routePath) => {
  console.log('routePath', routePath, props.basePath)
  if (isExternal(routePath)) {
    return routePath
  }
  
  // 如果 basePath 是根路径，直接返回 routePath（它会自动变成绝对路径）
  if (props.basePath === '/') {
    const result = '/' + routePath
    return result
  }
  
  // 如果 routePath 已经是绝对路径，直接返回
  if (routePath.startsWith('/')) {
    return routePath
  }
  
  // 正常的路径拼接
  const result = props.basePath + '/' + routePath
  
  return result
}
</script>
<style scoped>
:deep(.el-menu-item) {
  padding-left: 50px!important;
}

/* 折叠状态下的弹出菜单样式 */
:deep(.collapse-popper) {
  margin-left: 0!important;
}

:deep(.collapse-popper .el-menu) {
  padding: 5px 0;
}

:deep(.collapse-popper .el-menu-item) {
  padding-left: 20px!important;
  min-width: 180px;
}
</style>